package com.djhu.tool;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zw on 2017/12/8.
 */

public class CaseInsensitiveMap<K, V> extends HashMap<K, V>
{
    private static final long serialVersionUID = 4043263744224569870L;

    public CaseInsensitiveMap() {
        super();
    }

    public CaseInsensitiveMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
    }

    public CaseInsensitiveMap(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }

    public CaseInsensitiveMap(Map<? extends K, ? extends V> m) {
        super((int) (m.size() / 0.75));
        putAll(m);
    }

    public CaseInsensitiveMap(float loadFactor, Map<? extends K, ? extends V> m) {
        super(m.size(), loadFactor);
        putAll(m);
    }

    @Override
    public V get(Object key) {
        return super.get(lowerCaseKey(key));
    }

    @SuppressWarnings("unchecked")
    @Override
    public V put(K key, V value) {
        return super.put((K) lowerCaseKey(key), value);
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
            this.put(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public boolean containsKey(Object key) {
        return super.containsKey(lowerCaseKey(key));
    }

    private static Object lowerCaseKey(Object key) {
        if (key instanceof CharSequence) {
            key = key.toString().toLowerCase();
        }
        return key;
    }
}